import React, { useState, useRef } from 'react';
import { Card, Form, Input, Slider, Button, Upload, message, Row, Col } from 'antd';
import { SettingOutlined, UploadOutlined } from '@ant-design/icons';
import type { UploadFile, UploadProps } from 'antd';
import CommonTour, { TourGuideButton } from '@/components/CommonTour';

const ReferenceBackground: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [imageUrl, setImageUrl] = useState<string>('');
  const [uploadedFile, setUploadedFile] = useState<UploadFile[]>([]);
  const [similarity, setSimilarity] = useState<number>(80);
  const [tourVisible, setTourVisible] = useState(false);
  
  // Tour相关的ref引用
  const uploadRef = useRef<HTMLDivElement>(null);
  const similarityRef = useRef<HTMLDivElement>(null);
  const descriptionRef = useRef<HTMLDivElement>(null);
  const submitRef = useRef<HTMLButtonElement>(null);
  const resultRef = useRef<HTMLDivElement>(null);
  
  // 组织所有ref为一个对象
  const tourRefs = {
    upload: uploadRef,
    similarity: similarityRef,
    description: descriptionRef,
    submit: submitRef,
    result: resultRef,
  };
  
  // 显示导览
  const showTour = () => {
    // 添加短暂延迟确保DOM已渲染
    setTimeout(() => setTourVisible(true), 100);
  };
  
  // Tour步骤配置
  const tourSteps = [
    {
      key: 'upload',
      title: '上传参考图片',
      description: '请上传一张您希望作为参考的图片，系统将基于此图片生成相似风格的背景。',
      cover: <img src="https://gw.alipayobjects.com/zos/rmsportal/WXoqXTHrSnRcUwEaQgXJ.png" alt="上传参考" />,
    },
    {
      key: 'similarity',
      title: '设置相似度',
      description: '调整滑块控制生成图片与参考图片的相似度，数值越高相似度越高。',
      cover: <img src="https://gw.alipayobjects.com/zos/rmsportal/WXoqXTHrSnRcUwEaQgXJ.png" alt="相似度设置" />,
    },
    {
      key: 'description',
      title: '补充描述',
      description: '输入更详细的描述文本，帮助AI更好地理解您的需求和期望效果。',
      cover: <img src="https://gw.alipayobjects.com/zos/rmsportal/WXoqXTHrSnRcUwEaQgXJ.png" alt="补充描述" />,
    },
    {
      key: 'submit',
      title: '生成按钮',
      description: '点击此按钮开始生成与参考图片风格相似的背景图片。',
      cover: <img src="https://gw.alipayobjects.com/zos/rmsportal/WXoqXTHrSnRcUwEaQgXJ.png" alt="生成按钮" />,
    },
    {
      key: 'result',
      title: '生成结果',
      description: '右侧区域将显示生成的背景图片，您可以下载或重新生成。',
      cover: <img src="https://gw.alipayobjects.com/zos/rmsportal/WXoqXTHrSnRcUwEaQgXJ.png" alt="生成结果" />,
    },
  ];
  
  // 表单提交处理
  const handleSubmit = (values: any) => {
    if (uploadedFile.length === 0) {
      message.error('请先上传参考图片！');
      return;
    }
    
    setLoading(true);
    
    // 模拟图片生成过程
    setTimeout(() => {
      // 这里应该是调用AI生成图片的API
      // 现在使用占位图模拟
      setImageUrl('https://via.placeholder.com/800x600?text=Reference+Based+Background');
      message.success('背景图片生成成功！');
      setLoading(false);
    }, 2000);
  };
  
  // 上传配置
  const uploadProps: UploadProps = {
    name: 'file',
    accept: 'image/*',
    listType: 'picture',
    maxCount: 1,
    beforeUpload: (file) => {
      const isImage = file.type.startsWith('image/');
      if (!isImage) {
        message.error('请上传图片文件！');
      }
      return isImage;
    },
    onChange(info) {
      if (info.file.status === 'done') {
        setUploadedFile(info.fileList);
        message.success(`${info.file.name} 文件上传成功`);
      } else if (info.file.status === 'error') {
        message.error(`${info.file.name} 文件上传失败`);
      }
    },
    onRemove: () => {
      setUploadedFile([]);
      return true;
    },
  };
  
  // 相似度变化处理
  const handleSimilarityChange = (value: number) => {
    setSimilarity(value);
  };
  
  return (
    <div style={{ padding: 24 }}>
      <div style={{ marginBottom: 24 }}>
        <h1 style={{ fontSize: 28, fontWeight: 'bold', marginBottom: 8 }}>
          <SettingOutlined style={{ marginRight: 8 }} /> 参考背景生成<TourGuideButton onClick={showTour} />
        </h1>
        <p style={{ color: '#666' }}>上传参考图片，生成相似风格的背景图片</p>
      </div>
      
      <Row gutter={[24, 24]}>
        <Col xs={24} md={12}>
          <Card title="参考设置" style={{ height: '100%' }}>
            <Form layout="vertical" onFinish={handleSubmit}>
              <Form.Item
                label="上传参考图片"
                rules={[{ required: true, message: '请上传参考图片' }]}
              >
                <div ref={uploadRef}>
                  <Upload {...uploadProps}>
                    <Button icon={<UploadOutlined />}>点击上传</Button>
                  </Upload>
                </div>
              </Form.Item>
              
              <Form.Item
                label={`相似度设置: ${similarity}%`}
                tooltip="控制生成图片与参考图片的相似度"
              >
                <div ref={similarityRef}>
                  <Slider
                    min={30}
                    max={100}
                    value={similarity}
                    onChange={handleSimilarityChange}
                    marks={{
                      30: '30%',
                      50: '50%',
                      70: '70%',
                      80: '80%',
                      90: '90%',
                      100: '100%',
                    }}
                  />
                </div>
              </Form.Item>
              
              <Form.Item
                label="补充描述"
              >
                <div ref={descriptionRef}>
                  <Input.TextArea rows={4} placeholder="输入更详细的描述，帮助AI更好地理解您的需求" />
                </div>
              </Form.Item>
              
              <Form.Item>
                <Button ref={submitRef} type="primary" htmlType="submit" loading={loading} block>
                  生成相似背景
                </Button>
              </Form.Item>
            </Form>
          </Card>
        </Col>
        
        <Col xs={24} md={12}>
          <Card title="生成结果" style={{ height: '100%' }}>
            <div ref={resultRef} style={{ 
              display: 'flex', 
              alignItems: 'center', 
              justifyContent: 'center', 
              height: '400px', 
              backgroundColor: '#f0f2f5',
              borderRadius: 8,
              overflow: 'hidden'
            }}>
              {loading ? (
                <div style={{ textAlign: 'center' }}>
                  <p>正在生成背景图片，请稍候...</p>
                </div>
              ) : imageUrl ? (
                <img 
                  src={imageUrl} 
                  alt="生成的背景图片" 
                  style={{ maxWidth: '100%', maxHeight: '100%', objectFit: 'contain' }}
                />
              ) : (
                <div style={{ textAlign: 'center', color: '#999' }}>
                  <p>配置完成后，点击"生成相似背景"按钮获取结果</p>
                </div>
              )}
            </div>
            
            {imageUrl && (
              <div style={{ marginTop: 16, textAlign: 'center' }}>
                <Button style={{ marginRight: 8 }}>下载图片</Button>
                <Button type="primary">重新生成</Button>
              </div>
            )}
          </Card>
        </Col>
      </Row>
      
      {/* Tour导览组件 */}
      <CommonTour
        open={tourVisible}
        onClose={() => setTourVisible(false)}
        steps={tourSteps}
        targetRefs={tourRefs}
      />
    </div>
  );
};

export default ReferenceBackground;